<?php
class page
{
    protected $db;
    protected $cache;
    protected $req;
    protected $user_info = array();
    protected $user_id = 0;
    protected $is_vip = false;
    protected $user_check_required = true;
    protected $admin_check_required = false;
    protected $host;
    
    protected $s_status = 'success';
    protected $f_status = 'failure';

    public function __call ($name, $arguments) {
        G::http404("未找到页面！");
    }

    public function __construct () {
    	$this->host = G::get_host();
    	$this->req = $_REQUEST;
		$this->db = new PDO(_DSN, _DB_USERNAME, _DB_PASSWORD, array(
			PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"
		));
		$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        $this->cache = new Memcache();
        $this->cache->connect(CACHE_HOST, CACHE_PORT);
		
//         $this->user_info = $this->getUserInfo();
//         if(!$this->user_info){
//         	die('missing device_id');
//         }
//         if (isset($this->user_info['dev_id'])) {
//             $this->user_id = $this->user_info['id'];
//             $this->$is_vip = $this->user_info['is_vip'];
//         }
    }
	
	/**
	 * json输出
	 * @param int $status
	 * @param string $message = ''
	 * @param array $data = array()
	 * @param bool $is_exit = true
	 */
	protected function json_out ($status, $message = '', $data = array(), $is_exit = true) {
		G::http_json();
		echo json_encode(compact('status', 'message', 'data'));
		if ($is_exit) exit();
	}
	
	/**
	 * 获取并返回语言变量，默认返回所有语言变量
	 * @param string $key = null
	 * @return string
	 */
	protected function L ($key = null, $replace = null) {
		$l = $this->tpl->getConfigVars($key);
		if ($replace) {
			if (!$key) {
				foreach ($l as $k => $v) {
					foreach ($replace as $r_k => $r_v) {
						$l[$k] = str_replace('['.$r_k.']', $r_v, $v);
					}
				}
			} else {
				foreach ($replace as $r_k => $r_v) {
					$l[$k] = str_replace('['.$r_k.']', $r_v, $v);
				}
			}
		}
		return $l;
	}

    function getUserInfo(){
    	$device_id = $this->req['device_id'];
    	if(!$device_id){
    		return false;
    	}
    	$id = '';
    	$row = $this->db->query("SELECT id, uid FROM `account` WHERE `device_id` = $device_id")->fetch(PDO::FETCH_ASSOC);
    	if (!$row) {
    		$this->db->query("INSERT INTO `account` (device_id, create_time) VALUES ('$device_id', now())");
    		$id = $this->db->lastInsertId();
    		$this->db->query("UPDATE `account` SET uid=id WHERE device_id = '{$device_id}' LIMIT 1 ");
    		$this->db->query("INSERT INTO `user` (uid, create_time) VALUES ('{$id}', now())");
    	}else{
    		$id = $row['uid'];
    	}
    	$user = $this->db->query("SELECT t1.uid, t1.gold, t1.book_count, t2.is_vip FROM `user` t1 LEFT JOIN `vip` t2 ON t1.uid = t2.uid WHERE t1.uid = '{$id}' ")->fetch(PDO::FETCH_ASSOC);
    	
    	if($user['is_vip']){
    		$user['book_count'] += 47;
    	}
    	
    	return $user;
    }
	
	/**
	 * 记录系统操作日志
	 * @param mixed $data
	 */
	protected function log ($data, $extra = null) {
		$date = date('Y-m-d');
		$time = date('H:i:s');
		$sudo_dev_id = $this->is_admin;
		$dev_id = $this->user_id;
		$ip = G::client_ip();
		$ua = $_SERVER['HTTP_USER_AGENT'];
		$act = preg_replace('%\?.+$%', '', $_SERVER['REQUEST_URI']);
		$uri = $_SERVER['REQUEST_URI'];
		return $this->db->prepare("INSERT INTO `log` (".
				"`date`, `time`, `sudo_dev_id`, `dev_id`, `ip`, `ua`, `act`, `uri`, `data`, `extra`) VALUES (".
				":date, :time, :sudo_dev_id, :dev_id, :ip, :ua, :act, :uri, :data, :extra)")
			->execute(compact('date', 'time', 'sudo_dev_id', 'dev_id', 'ip', 'ua', 'act', 'uri', 'data', 'extra'));
	}
	
	protected function memGet($key){
		return $this->cache->get($key);
	}
	
	protected function memSet($key, $value, $expire=86400, $isCompressed=false){
		$flag = 0;
		if($isCompressed)$flag = MEMCACHE_COMPRESSED;
		return $this->cache->set($key, $value, $flag, $expire);
	}
}
